package projorientado.ocr.vfeature.impl.comparator;

import projorientado.ocr.vfeature.FeaturesComparator;
import projorientado.ocr.vfeature.FeaturesPair;
import projorientado.ocr.vfeature.SequentialFeatures;

public class CorrelationComparator implements FeaturesComparator {
    
    public static final CorrelationComparator instance = new CorrelationComparator();

    public float compareFeatures(SequentialFeatures s1, SequentialFeatures s2) {
        float value = fullFeaturesCorrelation(s1,s2);
        if(Float.isNaN(value)) {
            // problema quando todos os pontos são iguais
            return EuclideanComparator.instance.compareFeatures(s1, s2);
        }
        if(value < 0)
            value = 0;
        return 100*(1-value);
    }
            
    public static float fullFeaturesCorrelation(SequentialFeatures s1, SequentialFeatures s2) {
        int len = s1.featuresSize();
        
        float mi1 = 0, mi2 = 0;
        
        for(int i = 0; i < len; i++) {
            mi1 += s1.getFeature(i);
            mi2 += s2.getFeature(i);
        }
        
        mi1 /= (float)(len);
        mi2 /= (float)(len);
        
        double num = 0;
        double pdem1 = 0, pdem2 = 0;
        
        for(int i = 0; i < len; i++) {
            float diff1 = (s1.getFeature(i) - mi1);
            float diff2 = (s2.getFeature(i) - mi2);
            num += diff1*diff2;
            pdem1 += diff1*diff1;
            pdem2 += diff2*diff2;
        }
        
        double dem = Math.sqrt(pdem1)*Math.sqrt(pdem2);
        
        return (float)(num/dem);
    }
}
